package com.sumer.psychology.photo.infrastructure.persistence.hibernate;

import com.sumer.psychology.common.persistence.hibernate.AbstractHibernateRepository;
import com.sumer.psychology.photo.domain.model.Album;
import com.sumer.psychology.photo.domain.model.AlbumAvailability;
import com.sumer.psychology.photo.domain.model.AlbumId;
import com.sumer.psychology.photo.domain.model.AlbumRepository;
import org.hibernate.Query;

import java.util.UUID;

/**
 * 相册资源库
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/9/1
 * Time: 15:00
 */
public class HibernateAlbumRepository extends AbstractHibernateRepository implements AlbumRepository {
    @Override
    public AlbumId nextIdentity() {
        return new AlbumId(UUID.randomUUID().toString());
    }

    @Override
    public void add(Album anAlbum) {
        session().saveOrUpdate(anAlbum);
    }

    @Override
    public Album ofAlbumId(AlbumId albumId) {
        Query query = session()
                .createQuery("from Album where albumId=:albumId and availability=:availability")
                .setParameter("albumId", albumId)
                .setParameter("availability", AlbumAvailability.ACTIVE);

        return (Album) query.uniqueResult();
    }
}
